package com.xyh.transaction.service.imp;

import com.xyh.transaction.entity.LoginUser;
import com.xyh.transaction.entity.Permission;
import com.xyh.transaction.entity.Role;
import com.xyh.transaction.entity.User;
import com.xyh.transaction.exception.UserNotFoundException;
import com.xyh.transaction.mapper.PermissionMapper;
import com.xyh.transaction.mapper.RoleMapper;
import com.xyh.transaction.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findByName(username);

        if (user == null) {
            throw new UserNotFoundException("用户【" + username + "】不存在");
        }

//        List<String> list = Arrays.asList("test", "admin");
        // 添加权限
        Set<Permission> permissions = permissionMapper.findByUserId(user.getId());
        Set<Role> roleList = roleMapper.findRoleByUserId(user.getId());

        return new LoginUser(user, roleList, permissions);
    }
}
